import request from '@/utils/request';
import {API_RECEIPT} from './config';

// 收货单查询参数
export interface ReceiptQueryParams {
    pageNum?: number;
    pageSize?: number;
    receiptNumber?: string;
    supplierName?: string;
    orderId?: string;
    status?: string;
    startDate?: string;
    endDate?: string;
}

// 收货单明细项
export interface ReceiptItem {
    id?: string;
    receiptId?: string;
    itemName: string;
    specification?: string;
    unit: string;
    quantity: number;
    unitPrice: number;
    total: number;
}

// 收货单数据
export interface Receipt {
    id?: string;
    receiptNumber: string;
    orderId?: string;
    orderNumber?: string;
    supplierName: string;
    status?: string;
    totalAmount: number;
    items?: ReceiptItem[];
}

/**
 * 获取收货单列表
 * @param params 查询参数
 */
export function getReceiptList(params: ReceiptQueryParams) {
    return request({
        url: API_RECEIPT.PAGE,
        method: 'get',
        params
    }).then(response => {
        // 确保返回结构正确
        if (response && response.code === 200) {
            // 情况1: 后端返回的是 {list: [...], total: ...} 格式
            if (response.data && response.data.list && Array.isArray(response.data.list)) {
                response.data = {
                    records: response.data.list,
                    total: response.data.total || response.data.list.length
                };
            }
            // 情况2: 后端直接返回数组格式
            else if (Array.isArray(response.data)) {
                response.data = {
                    records: response.data,
                    total: response.data.length
                };
            }
            // 情况3: 已有records字段但可能为null或undefined
            else if (response.data && !response.data.records) {
                console.warn('收货单数据结构不完整，records字段缺失，初始化为空数组');
                response.data.records = [];
                response.data.total = response.data.total || 0;
            }

            // 确保records是数组类型
            if (response.data && response.data.records && !Array.isArray(response.data.records)) {
                console.warn('records字段不是数组类型，进行修正');
                response.data.records = [];
                response.data.total = 0;
            }
        }

        return response;
    }).catch(error => {
        console.error('getReceiptList请求失败:', error);
        throw error;
    });
}

/**
 * 获取收货单详情
 * @param id 收货单ID
 */
export function getReceiptDetail(id: string) {
    return request({
        url: API_RECEIPT.DETAIL(id),
        method: 'get'
    });
}

// // 为兼容性添加别名
// export const getReceiptById = getReceiptDetail;

/**
 * 创建收货单
 * @param data 收货单数据
 */
export function createReceipt(data: Receipt) {
    return request({
        url: API_RECEIPT.CREATE,
        method: 'post',
        data
    });
}

/**
 * 更新收货单
 * @param id 收货单ID
 * @param data 收货单数据
 */
export function updateReceipt(id: string, data: Receipt) {
    return request({
        url: API_RECEIPT.UPDATE(id),
        method: 'put',
        data
    });
}

/**
 * 删除收货单
 * @param id 收货单ID
 */
export function deleteReceipt(id: string) {
    return request({
        url: API_RECEIPT.DELETE(id),
        method: 'delete'
    });
}

/**
 * 批量删除收货单
 * @param ids 收货单ID数组
 */
export function batchDeleteReceipt(ids: string[]) {
    return request({
        url: API_RECEIPT.BATCH_DELETE,
        method: 'delete',
        data: ids
    });
}

/**
 * 收货单验收
 * @param id 收货单ID
 * @param status 验收状态
 */
export function acceptReceipt(id: string, status: string) {
    return request({
        url: `${API_RECEIPT.BASE}/${id}/accept`,
        method: 'put',
        params: {status}
    });
}

/**
 * 导出收货单
 * @param params 查询参数
 */
export function exportReceipt(params: ReceiptQueryParams) {
    return request({
        url: `${API_RECEIPT.BASE}/export`,
        method: 'get',
        params,
        responseType: 'blob',
        headers: {
            'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        }
    });
}

// /**
//  * 获取收货单状态统计
//  */
// export function getReceiptStatusStatistics() {
//     return request({
//         url: `${API_RECEIPT.BASE}/statistics/status`,
//         method: 'get'
//     });
// }
//
// /**
//  * 获取收货单总金额
//  */
// export function getTotalReceiptAmount() {
//     return request({
//         url: `${API_RECEIPT.BASE}/total-amount`,
//         method: 'get'
//     });
// }
//
// /**
//  * 按供应商统计收货单
//  * @param limit 限制返回的供应商数量
//  */
// export function getReceiptStatsBySupplier(limit: number = 10) {
//     return request({
//         url: `${API_RECEIPT.BASE}/by-supplier`,
//         method: 'get',
//         params: {limit}
//     });
// }
//
// /**
//  * 根据订单ID获取关联收货单
//  * @param orderId 订单ID
//  */
// export function getReceiptsByOrderId(orderId: string): Promise<any> {
//     return request({
//         url: `${API_RECEIPT.BASE}/order/${orderId}`,
//         method: 'get'
//     });
// }

/**
 * 根据订单编号搜索收货单
 * @param orderNumber 订单编号
 */
export function findReceiptsByOrderNumber(orderNumber: string): Promise<any> {
    // 使用通用查询接口，将订单编号作为参数传递
    return request({
        url: `${API_RECEIPT.BASE}/search`,
        method: 'post',
        data: {orderNumber}
    });
} 